package Interfaz;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.EventObject;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;

import models.Logros;

import org.hibernate.Session;
import org.hibernate.Transaction;

import connection.HibernateUtil;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class LogrosWindow extends JFrame{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
    private	LogroPanel logroPanel;
	
    private JPanel panel;
    
	private JLabel actionBar;
	private JLabel marcoUser;
	private JLabel nombreUsuario;
	private JLabel logoSmall;
	private JButton find;
	private JTextField findText;
	
	private JTable logrosTable;
	private JTableHeader header;
	private JScrollPane scroll;
	private JLabel fastView;
	
	private List<Logros> logros;

	public Session DAO;	
	Transaction tx;
	private JButton btnNewButton;
	private JLabel imagenLabel;

	public LogrosWindow exec;
	private static final String serverURLBase="http://localhost/api/"; 

	// Declarar variables del fastView END//
	public LogrosWindow(){
		try{
			initJFrameComponents();
		}catch(Exception e){
			JOptionPane.showMessageDialog(null, "No hay logros en la base de datos");	
	}
	}
	public void initJFrameComponents() {
	
		panel = new JPanel();
		actionBar = new JLabel();
		marcoUser = new JLabel();
		logoSmall = new JLabel(new ImageIcon(getClass().getResource(
				"raw/logo_small.jpg")));
		nombreUsuario = new JLabel("Gesti�n de Logros");
		find = new JButton();
		findText = new JTextField();
		fastView = new JLabel(new ImageIcon(getClass().getResource(
				"raw/fastView.png")));
		imagenLabel = new JLabel();
		// Instanciar declaraciones END//
		// Asignar propiedades
		this.setMinimumSize(new Dimension(800, 600)); 
		
		actionBar.setBackground(Color.BLACK);
		actionBar.setForeground(Color.BLACK);
		actionBar.setBounds(0, 0, 800, 32);
		actionBar.setOpaque(true);
		
		marcoUser.setBackground(new Color(0xEEEEEE));
		marcoUser.setForeground(new Color(0xEEEEEE));
		marcoUser.setBounds(32, 10, 98, 98);
		marcoUser.setOpaque(true);

		logoSmall.setBounds(36, 14, 90, 90);

		nombreUsuario.setBounds(150, 3, 256, 25);
		nombreUsuario.setForeground(Color.WHITE);
		nombreUsuario.setFont(new Font("Serif", Font.BOLD, 18));

		find.setBounds(768, 0, 32, 32);
		find.setOpaque(true);
		find.setBackground(Color.GRAY);
		find.setForeground(Color.WHITE);
		find.setBorder(null);
		find.setIcon(new ImageIcon(getClass().getResource("raw/find.png")));
		findText.setBounds(668, 0, 100, 32);
		findText.setBorder(null);
		findText.setForeground(Color.WHITE);
		findText.setBackground(Color.GRAY);

		fastView.setBounds(280, 90, 481, 448);
		fastView.setOpaque(false);
		imagenLabel.setBackground(Color.WHITE);
		imagenLabel.setBounds(650, 94, 100, 95);
		imagenLabel.setOpaque(true);
		
		DAO = HibernateUtil.configureSessionFactory().getCurrentSession();
		 tx = DAO.beginTransaction();
		 logros = DAO.createQuery("FROM Logros logro WHERE logro.activado=true").list();
		 tx.commit();
		// Instanciar declaraciones
		//panel = new JPanel();
		 
		logroPanel = new LogroPanel(this,logros.get(0));
		logroPanel.setBounds(300,230, 350, 350);
		// Inflar la lista de datos y el scrollview
		//inflateList();
		// Asignar propiedades END//
		this.getContentPane().setLayout(null);
		this.getContentPane().add(logoSmall);
		this.getContentPane().add(findText);
		this.getContentPane().add(find);
		this.getContentPane().add(nombreUsuario);
		this.getContentPane().add(marcoUser);
		this.getContentPane().add(actionBar);
		this.getContentPane().add(imagenLabel);
		this.getContentPane().add(fastView);
		this.getContentPane().add(logroPanel);
		
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		this.setBounds(((d.width / 2) - 400), ((d.height / 2) - 300), 800, 600);
		panel.setBackground(Color.WHITE);

		// Agragarlas a la interfaz END//

		this.getContentPane().setBackground(Color.WHITE);
		
		scroll = new JScrollPane();
		scroll.setBounds(20, 140, 180, 400);
		getContentPane().add(scroll);
		
		logrosTable = new JTable(){ public boolean isCellEditable(int rowIndex, int colIndex) {
	        return false;   //Disallow the editing of any cell
	    }};
		logrosTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		logrosTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			
			public void valueChanged(ListSelectionEvent arg0) {
				int filaSeleccionada=logrosTable.getSelectedRow();
				if (filaSeleccionada < 0){
					return;
				}
				
				getContentPane().remove(logroPanel);
				logroPanel = new LogroPanel(LogrosWindow.this,logros.get(filaSeleccionada));
				logroPanel.setBounds(300,230, 350, 350);
				getContentPane().add(logroPanel);
				getContentPane().validate();
				repaint();
			}
		});
	
		String[][] logrosArray=new String[logros.size()][2];
		int contador=0;
		
		for (Logros logro : logros) {
			logrosArray[contador][0]= ""+logro.getId();
			logrosArray[contador][1]= logro.getNombre();
			
			contador++;
		}
		logrosTable.setModel(new DefaultTableModel(
			logrosArray,
			new String[] {
				"Id", "nombre"
			}
		));
		scroll.setViewportView(logrosTable);
		getContentPane().add(scroll);
		
		btnNewButton = new JButton("");
		btnNewButton.setIcon(new ImageIcon(LogrosWindow.class.getResource("/Interfaz/raw/nuevo.png")));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				getContentPane().remove(logroPanel);
				getContentPane().validate();
				logroPanel = new LogroPanel(LogrosWindow.this,null);
				logroPanel.setBounds(300,230, 350, 350);
				getContentPane().add(logroPanel);
				logroPanel.revalidate();
				getContentPane().validate();
				imagenLabel.setIcon(null);
				repaint();
			}
		});
		btnNewButton.setBounds(210, 143, 43, 46);
		getContentPane().add(btnNewButton);
		
		
		
		this.setVisible(true);
		this.setResizable(false);
		
	
	}
	public void refrescarLogros() {
		DAO = HibernateUtil.configureSessionFactory().getCurrentSession();
		 tx = DAO.beginTransaction();
		 logros = DAO.createQuery("FROM Logros logro WHERE logro.activado=true").list();
		 tx.commit();
		String[][] logrosArray=new String[logros.size()][2];
		int contador=0;
		
		for (Logros logro : logros) {
			logrosArray[contador][0]= ""+logro.getId();
			logrosArray[contador][1]= logro.getNombre();
			
			contador++;
		}
		logrosTable.setModel(new DefaultTableModel(
			logrosArray,
			new String[] {
				"Id", "nombre"
			}
		));
		repaint();
	}
	public void establecerImagen(String urlImg) {
		if (urlImg!= null && !urlImg.trim().equals("")){
			try {
				imagenLabel.setOpaque(true);
				
				ImageIcon imageIcon = new ImageIcon(ImageIO.read(new URL(serverURLBase+urlImg)));
				Image image = imageIcon.getImage().getScaledInstance(90, 90, Image.SCALE_SMOOTH);
				imageIcon.setImage(image);
				imagenLabel.setIcon(imageIcon);
				imagenLabel.repaint();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			imagenLabel.setIcon(null);
		}
		
	}
	public void guardarLogroTest(String nombre, String puntos, String descripcion, String imagen) {
		Logros logro = new Logros();
		logro.setActivado(true);
				
		

		logro.setNombre(nombre);
		
		logro.setDescripcion(descripcion);
		
		logro.setNumeroPuntos(Integer.parseInt(puntos));
		logro.setUrlImg(imagen);
	
		DAO = HibernateUtil.configureSessionFactory().getCurrentSession();
		tx = DAO.beginTransaction();
		DAO.persist(logro);
		tx.commit();
		//JOptionPane.showMessageDialog(null,"El logro se ha creado exitosamente");
		
	}
	
	

	
}
